import os

from loguru import logger
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

from common import conf

DB_NAME = 'adb'
DB_HOST = 'db:5432' if conf.check_is_production() else '127.0.0.1:5432'
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../data/db/', 'adb.db'))
logger.info("db path is {}".format(db_path))
# SQLALCHEMY_DATABASE_URL = "sqlite:///{}".format(db_path)
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:123@{}/{}".format(DB_HOST, DB_NAME)
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"


engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_size=200)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

if database_exists(engine.url):
    logger.info("db='{}' is already exit, no need create".format(DB_NAME))
else:
    create_database(engine.url)
    logger.info("create db={}, now exist flag={}".format(DB_NAME, database_exists(engine.url)))


class MySuperContextManager:
    def __init__(self):
        self.db = SessionLocal()

    def __enter__(self):
        return self.db

    def __exit__(self, exc_type, exc_value, traceback):
        self.db.close()


def get_db():
    with MySuperContextManager() as db:
        yield db
